package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.BrandDao;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key= (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            QueryWrapper<BrandEntity> brandEntityQueryWrapper = new QueryWrapper<>();
            brandEntityQueryWrapper.eq("brand_id",key).or().like("name",key).or().like("descript",key).or().eq("first_letter",key);
            IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params), brandEntityQueryWrapper);
            return new PageUtils(page);
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                new QueryWrapper<BrandEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void updateByIdCascade(BrandEntity brand) {
        //更新pms_category_brand_relation中的brandname
        BrandEntity oldBrand = baseMapper.selectById(brand.getBrandId());
        String oldBrandName = oldBrand.getName();
        baseMapper.updateById(brand);
        String name = brand.getName();
        if (!oldBrandName.equals(name)){
            categoryBrandRelationService.updateBrand(brand);
        }
    }

}